#include <iostream>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "comm.h"

using namespace std;

bool Makefifo()
{
    // 创建管道
    int n = mkfifo(FILENAME, 0666);
    if (n < 0)
    {
        cerr << "errno: " << errno << ", errstring: " << strerror(errno) << endl;
        return false;  
    }

    cout << "mkfifo success..." << endl;
    return true;
}

int main()
{
    // 打开管道
Start:
    int rfd = open(FILENAME, O_RDONLY); // 打开成功就直接用，失败就创建
    if (rfd < 0)
    {
        cerr << "errno: " << errno << ", errstring: " << strerror(errno) << endl;
        if (Makefifo()) goto Start;
        else return 1;  // 创建失败
    }
    cout << "open fifo success... read" << endl;

    // 读管道
    char buffer[1024];
    while(true)
    {
        ssize_t s = read(rfd, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "Client say# " << buffer << endl;
        }
        // 写端退出，我也退出
        else if (s == 0)
        {
            cout << "client quit, server quit too..." << endl;
            break;
        }
    }

    close(rfd);
    cout << "close fifo success... read" << endl;

    return 0;
}